<template>
  <div class="chat-container">
    <div class="chat-main">
      <!-- 左侧用户列表 -->
      <div class="user-list">
        <div class="user-list-header">
          <el-input
            placeholder="搜索用户"
            prefix-icon="el-icon-search"
            v-model="searchUser"
            clearable
          ></el-input>
        </div>
        <div class="user-list-content">
          <div>
            <div
              class="user-item"
              v-for="user in filteredUsers"
              :key="user.id"
              :class="{ active: currentUser.id === user.id }"
              @click="selectUser(user)"
            >
              <el-avatar :size="40" :src="user.avatar"></el-avatar>
              <div class="user-info">
                <span class="username">{{ user.name }}</span>
                <span class="last-msg">{{ user.lastMessage }}</span>
              </div>
              <div class="user-status" :class="user.status"></div>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧聊天区域 -->
      <div class="chat-area">
        <div class="chat-header-info">
          <div v-if="currentUser.id">
            <el-avatar :size="40" :src="currentUser.avatar"></el-avatar>
            <span class="chat-username">{{ currentUser.id }}</span>
            <span class="status-dot" :class="currentUser.status"></span>
          </div>
          <div v-else>请选择聊天用户</div>
        </div>

        <!-- 消息展示区域 -->
        <div class="message-area" ref="messageArea">
          <div>
            <div
              v-for="(message, index) in currentMessages"
              :key="index"
              class="message-item"
              :class="{ 'message-right': message.type == 'admin' }"
            >
              <div class="message-content">
                <div class="message-text">{{ message.content }}</div>
                <div class="message-time">{{ message.time }}</div>
              </div>
              <el-avatar
                v-if="!message.type == 'admin'"
                :size="36"
                :src="currentUser.avatar"
              ></el-avatar>
              <el-avatar v-else :size="36" :src="myAvatar"></el-avatar>
            </div>
          </div>
        </div>

        <!-- 消息输入区域 -->
        <div class="message-input">
          <el-input
            type="textarea"
            :rows="3"
            placeholder="输入消息..."
            v-model="inputMessage"
            @keyup.enter.native="sendMessage"
            :disabled="!currentUser.id"
          ></el-input>
          <div class="send-btn">
            <el-button
              type="primary"
              @click="sendMessage"
              :disabled="!inputMessage || !currentUser.id"
              >发送</el-button
            >
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'ChatPage',
  data() {
    return {
      searchUser: '',
      inputMessage: '',
      myAvatar:
        'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
      currentUser: {},
      users: [
        {
          id: 1,
          name: '张三',
          avatar:
            'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
          status: 'online',
          lastMessage: '你好，最近怎么样？'
        },
        {
          id: 2,
          name: '李四',
          avatar:
            'https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png',
          status: 'offline',
          lastMessage: '项目进展如何？'
        },
        {
          id: 3,
          name: '王五',
          avatar:
            'https://cube.elemecdn.com/e/f3/43eaa8a00df2f5e3c8f5d0b58162dpng.png',
          status: 'online',
          lastMessage: '明天开会别忘了'
        },
        {
          id: 4,
          name: '赵六',
          avatar:
            'https://cube.elemecdn.com/2/11/6531b15b26e3f79b48bde5d87b8e3png.png',
          status: 'busy',
          lastMessage: '资料已发送'
        }
      ],
      messages: {
        1: [
          {
            content: '你好，最近怎么样？',
            time: '10:30',
            isMe: false
          },
          {
            content: '还不错，你呢？',
            time: '10:32',
            isMe: true
          },
          {
            content: '我也挺好的，项目进展如何？',
            time: '10:33',
            isMe: false
          }
        ],
        2: [
          {
            content: '项目进展如何？',
            time: '昨天',
            isMe: false
          },
          {
            content: '正在按计划进行，下周可以完成第一阶段',
            time: '昨天',
            isMe: true
          }
        ],
        3: [
          {
            content: '明天开会别忘了',
            time: '星期二',
            isMe: false
          }
        ],
        4: [
          {
            content: '资料已发送',
            time: '星期一',
            isMe: false
          },
          {
            content: '收到了，谢谢',
            time: '星期一',
            isMe: true
          }
        ]
      },
      /* eslint-disable */
      //  type WebMessage struct {
      // 	Type        string    `json:"type"`
      // 	ContentType string    `json:"content_type"`
      // 	Content     any       `json:"content"`
      // 	ToId        int64     `json:"to_id"`
      // 	Time        time.Time `json:"time"`
      // }
      messageMap: {},
      webSocket: {
        url: 'ws://localhost:8899/ws',
        socket: null,
        heartbeatTimer: null
      }
    }
  },
  computed: {
    filteredUsers() {
      if (!this.searchUser) return this.messageMap
      return this.messageMap.filter((user) =>
        user.id.toLowerCase().includes(this.searchUser.toLowerCase())
      )
    },
    currentMessages() {
      // console.log(this.messageMap[this.currentUser.id])
      return this.currentUser.id
        ? this.messageMap[this.currentUser.id].message_list
        : []
    }
  },
  mounted() {
    this.connectWs()
  },
  beforeDestroy() {
    clearInterval(this.webSocket.heartbeatTimer)
    this.webSocket.socket.close()
  },
  methods: {
    connectWs() {
      this.webSocket.socket = new WebSocket(this.webSocket.url)
      console.log(this.webSocket)
      const socket = this.webSocket.socket
      socket.addEventListener('open', () => {
        console.log('socket已经打开')
        const msg = {
          type: 'firstAdmin',
          content_type: 'text',
          content: '',
          to_id: '',
          time: new Date()
        }
        socket.send(JSON.stringify(msg))

        // 开始心跳
        this.startHeartbeat()

        // setInterval(() => {
        //   msg.type = 'receive'
        //   msg.content = '收到请回复'
        //   msg.to_id = '1111111'
        //   socket.send(JSON.stringify(msg))
        // }, 5000)
      })

      this.webSocket.socket.addEventListener('message', (event) => {
        console.log('收到消息:', event.data)
        const data = JSON.parse(event.data)
        console.log(data)

        switch (data.type) {
          case 'firstAdmin':
            // console.log(data.content)
            this.messageMap = data.content.userList
            this.currentUser = {}
            break
          case 'heartbeatAdmin':
            console.log(data.content)
            this.messageMap = data.content.userList
            this.currentUser = {}
            break
          case 'user':
            const id = data.from_id
            // console.log(
            //   ,
            //   this.messageMap,
            //   this.messageMap[data.from_id]
            // )
            if (this.messageMap[id].message_list == null) {
              this.messageMap[id].message_list = []
            }
            this.messageMap[id].message_list.push(data)
            this.$nextTick(() => {
              this.scrollToBottom()
            })
          // console.log(this.messageMap)
        }
        // 	Type        string    `json:"type"`
        // 	ContentType string    `json:"content_type"`
        // 	Content     any       `json:"content"`
        // 	ToId        int64     `json:"to_id"`
        // 	Time        time.Time `json:"time"`
        // const msg = {
        //   type: 'send',
        //   content_type: 'text',
        //   content: '你好，请问有什么需要帮助的吗？',
        //   to_id: 111111,
        //   time: new Date()
        // }
        // socket.send(JSON.stringify(msg))
      })
    },
    selectUser(user) {
      this.currentUser = user
      this.$nextTick(() => {
        this.scrollToBottom()
      })
    },
    sendMessage() {
      if (!this.inputMessage.trim() || !this.currentUser.id) return

      const newMessage = {
        type: 'admin',
        content_type: 'text',
        content: this.inputMessage,
        to_id: this.currentUser.id,
        time: new Date()
      }

      // console.log(this.messageMap)
      if (this.messageMap[this.currentUser.id].message_list == null) {
        this.messageMap[this.currentUser.id].message_list = []
      }

      this.messageMap[this.currentUser.id].message_list.push(newMessage)
      this.webSocket.socket.send(JSON.stringify(newMessage))
      // 更新最后一条消息

      // const user = this.users.find((u) => u.id === this.currentUser.id)
      // if (user) {
      //   user.lastMessage = this.inputMessage
      // }

      this.inputMessage = ''
      this.$nextTick(() => {
        this.scrollToBottom()
      })
    },
    scrollToBottom() {
      const container = this.$refs.messageArea
      if (container) {
        container.scrollTop = container.scrollHeight
      }
    },
    getCurrentTime() {
      const now = new Date()
      const hours = now.getHours().toString().padStart(2, '0')
      const minutes = now.getMinutes().toString().padStart(2, '0')
      return `${hours}:${minutes}`
    },
    startHeartbeat() {
      // 清除旧定时器
      if (this.webSocket.heartbeatTimer) {
        clearInterval(this.webSocket.heartbeatTimer)
        this.webSocket.heartbeatTimer = null
      }

      // 每20秒跳动一下
      this.webSocket.heartbeatTimer = setInterval(() => {
        if (
          this.webSocket.socket &&
          this.webSocket.socket.readyState === WebSocket.OPEN
        ) {
          this.webSocket.socket.send(JSON.stringify({ type: 'heartbeatAdmin' }))
        } else {
          clearInterval(this.webSocket.heartbeatTimer)
        }
      }, 20000)
    }
  }
}
</script>

<style scoped>
.chat-container {
  width: 1000px;
  height: 600px;
  box-sizing: border-box;
  margin: 20px auto;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
}

.chat-header {
  padding: 15px;
  border-bottom: 1px solid #ebeef5;
  text-align: center;
  background-color: #409eff;
  color: white;
  border-radius: 4px 4px 0 0;
}

.chat-main {
  display: flex;
  flex: 1;
  overflow: hidden;
}

.user-list {
  width: 280px;
  border-right: 1px solid #ebeef5;
  display: flex;
  flex-direction: column;
}

.user-list-header {
  padding: 10px;
  border-bottom: 1px solid #ebeef5;
}

.user-list-content {
  flex: 1;
  overflow-y: auto;
}

.user-item {
  display: flex;
  align-items: center;
  padding: 12px;
  cursor: pointer;
  border-bottom: 1px solid #f5f5f5;
}

.user-item:hover {
  background-color: #f5f7fa;
}

.user-item.active {
  background-color: #ecf5ff;
}

.user-info {
  flex: 1;
  margin-left: 12px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.username {
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.last-msg {
  font-size: 12px;
  color: #909399;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.user-status {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  margin-left: 10px;
}

.user-status.online {
  background-color: #67c23a;
}

.user-status.offline {
  background-color: #909399;
}

.user-status.busy {
  background-color: #f56c6c;
}

.chat-area {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.chat-header-info {
  padding: 15px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  align-items: center;
}

.chat-header-info .el-avatar {
  margin-right: 10px;
}

.chat-username {
  font-size: 16px;
  font-weight: 500;
  margin-right: 10px;
}

.status-dot {
  display: inline-block;
  width: 8px;
  height: 8px;
  border-radius: 50%;
}

.status-dot.online {
  background-color: #67c23a;
}

.status-dot.offline {
  background-color: #909399;
}

.status-dot.busy {
  background-color: #f56c6c;
}

.message-area {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  background-color: #f5f5f5;
}

.message-item {
  display: flex;
  margin-bottom: 20px;
}

.message-right {
  flex-direction: row-reverse;
}

.message-content {
  max-width: 60%;
  margin: 0 10px;
}

.message-right .message-content {
  align-items: flex-end;
}

.message-text {
  padding: 10px 15px;
  border-radius: 4px;
  background-color: white;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  word-break: break-word;
}

.message-right .message-text {
  background-color: #409eff;
  color: white;
}

.message-time {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.message-input {
  padding: 15px;
  border-top: 1px solid #ebeef5;
}

.send-btn {
  margin-top: 10px;
  text-align: right;
}

.el-scrollbar {
  height: 100%;
}

.el-scrollbar__wrap {
  overflow-x: hidden;
}
</style>
